<script setup>
import { ref, onMounted, reactive } from "vue";
import {
  huiyuanIndex,
  shouyeIndex,
  huiyuanAdd,
  huiyuanUpdate,
  huiyuanDelete,
} from "@/api";
import tableValue from "@/components/tableValue.vue";
import { Plus } from "@element-plus/icons-vue";

// 传递子组件表格数据
const tableData = reactive([]);

// 传递子组件的列配置数组
const columns = [
  { prop: "cardno", label: "会员账号", width: "100" },
  { prop: "name", label: "姓名", width: "80" },
  // 头像列（特殊列，无 prop，用自定义模板）
  { label: "头像", width: "80", type: "image" },
  { prop: "createTime", label: "办卡时间", width: "120" },
  { prop: "sex", label: "性别", width: "80" },
  { prop: "year", label: "年龄", width: "80" },
  { prop: "phone", label: "联系方式", width: "120" },
  { prop: "height", label: "身高", width: "80" },
  { prop: "weight", label: "体重", width: "80" },
  { prop: "buytime", label: "购买课时", width: "80" },
  { prop: "buytime", label: "剩余课时", width: "80" },
  // 操作列（特殊列，无 prop）
  { label: "操作", type: "action" },
];

const formRef = ref();

onMounted(async () => {
  hyglTable();
});
// 信息条数
const total = ref(1);
// 搜索的字段信息
const SearchValue = ref("");

// 表格数据请求
// const hyglList = ref({ cardno: "", pageNum: 1, pageSize: 5 });

// 请求会员数据
const hyglTable = async (cardnos = "", page = null) => {
  const res = await huiyuanIndex({
    cardno: cardnos,
    pageNum: page || 1,
    pageSize: 5,
  });
  total.value = res.total;
  tableData.length = 0;
  Object.assign(tableData, res.data);
};

// 搜索功能
const searchType = (value) => {
  SearchValue.value = value;
  hyglTable(value.value);
};

// 新增功能
const dialogFormVisible = ref(false);

// 判断是新增还是编辑
const RowType = ref("");

// 点击了新增按钮触发
const adds = async (type = null) => {
  RowType.value = "会员新增";
  form.value.cardno = generateEightDigits();
  form.value.pass = "123456";
  form.value.sex = "男";
  if (type === null) {
    // 新增
    dialogFormVisible.value = true;
    await shouyeIndex().then((res) => {
      console.log(res.huiyuanshu);
      form.id = res.huiyuanshu + 1;
    });
  }
};

// 表单数据
const form = ref({});

// 随机生成八位数会员账号
function generateEightDigits() {
  return Math.floor(10000000 + Math.random() * 90000000);
}

// 头像
const handleAvatarSuccess = (e) => {
  form.value.hyimg = e.data;
};
// 图片上传的请求头
const headers = reactive({
  schoolid: 11,
  token:
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IjQ1NioqKkBxcS5jb20iLCJwaG9uZSI6IjEzNyoqKio1NDQ5IiwiaWQiOjEsInVzZXJuYW1lIjoiY2VzaGkxIiwibmlja25hbWUiOiIiLCJwYXNzd29yZCI6IjA5MTNmYWIyOWY4YWE5MmY5N2ZlNjQ2ODM5NDA5ZjM3MjZjNGQzZGM2NGY0NDlmMTA2MjJhNTUwMGM3NDBjMDIiLCJhdmF0YXIiOiIiLCJ3ZWl4aW5fdW5pb25pZCI6bnVsbCwic2V4Ijoi5pyq55-lIiwiZGVzYyI6IiIsInN0YXR1cyI6MSwiY3JlYXRlZF90aW1lIjoiMjAyMS0wMi0yMVQxNDowNDowMi4wMDBaIiwidXBkYXRlZF90aW1lIjoiMjAyMy0xMC0wNFQxNjo0ODo0MC4wMDBaIiwiaWF0IjoxNjk4NTYyOTU4fQ.MLAxkr9JkR9lIxEZbufSuBDB_kz-GR8UYEvwB3NslcA",
});
const delshow = ref(false); // 用show变量控制删除弹窗，默认关闭
// 点击了确定按钮触发,会员新增
const submit = () => {
  dialogFormVisible.value = false;
  console.log("表单提交");
  formRef.value.validate(async (valid) => {
    if (valid) {
      console.log("表单验证通过");
      if (RowType.value === "会员新增") {
        const res = await huiyuanAdd(form.value);
        if (res.code === 200) ElMessage.success(res.msg);
      } else {
        const res = await huiyuanUpdate(form.value);
        if (res.code === 200) ElMessage.success(res.msg);
      }
      hyglTable("", pagess.value);

      // 处理表单数据
      formRef.value.resetFields();
      form.value = {};
    } else {
      console.log("表单验证失败");
      return false;
    }
  });
};
// 编辑
const editType = (item) => {
  RowType.value = "会员编辑";
  dialogFormVisible.value = true;
  Object.assign(form.value, item);
};

// 会员删除
const delId = ref();
const deletes = (item) => {
  delId.value = item.id;
  delshow.value = true;
};
const handleConfirm = async () => {
  const res = await huiyuanDelete({ id: delId.value });
  delshow.value = false;
  if (res.code === 200) ElMessage.success(res.msg);
  hyglTable("", pagess.value);
};
// 表单校验
const rules = reactive({
  name: [
    { required: true, message: "输入不能为空", trigger: "blur" },
    { min: 2, max: 5, message: "请输入2-5个字符", trigger: "blur" },
  ],
  buytime: [
    { required: true, message: "输入不能为空", trigger: "blur" },
    { min: 0, message: "请输入合理的购买时间", trigger: "blur" },
  ],
  createTime: [{ required: true, message: "输入不能为空", trigger: "blur" }],
  height: [
    { required: true, message: "输入不能为空", trigger: "blur" },
    { min: 0, message: "请输入合理的身高", trigger: "blur" },
  ],
  hyimg: [{ required: true, message: "输入不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  weight: [
    { required: true, message: "输入不能为空", trigger: "blur" },
    { min: 0, message: "请输入合理的体重", trigger: "blur" },
  ],
  year: [
    { required: true, message: "输入不能为空", trigger: "blur" },
    { min: 0, message: "请输入合理的年龄", trigger: "blur" },
  ],
});
const pagess = ref(0);

const Page = async (pages) => {
  await hyglTable("", pages);
  pagess.value = pages;

  console.log(pages);
};
</script>

<template>
  会员管理
  <tableValue
    :textList="tableData"
    :columns="columns"
    :total="Number(total)"
    @SearchValue="searchType"
    @add="adds"
    @edit="editType"
    @delete="deletes"
    @PageType="Page"
  />

  <el-dialog v-model="dialogFormVisible" :title="RowType" width="800">
    <el-form :model="form" ref="formRef" :rules="rules">
      <el-form-item label="会员账号： " prop="cardno">
        <el-input v-model="form.cardno" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密 码： " prop="pass">
        <el-input v-model="form.pass" autocomplete="off" type="password" />
      </el-form-item>

      <el-form-item label="名 字： " prop="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性 别： " prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio value="男" size="large">男</el-radio>
          <el-radio value="女" size="large">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="电 话： " prop="phone">
        <el-input v-model="form.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="年 龄： " prop="year">
        <el-input v-model="form.year" autocomplete="off" />
      </el-form-item>
      <el-form-item label="身 高： " prop="height">
        <el-input v-model="form.height" autocomplete="off" />
      </el-form-item>
      <el-form-item label="体 重： " prop="weight">
        <el-input v-model="form.weight" autocomplete="off" />
      </el-form-item>
      <el-form-item label="购买课时： " prop="buytime">
        <el-input v-model="form.buytime" autocomplete="off" />
      </el-form-item>
      <el-form-item label="办卡时间： " prop="createTime">
        <el-date-picker
          v-model="form.createTime"
          type="date"
          placeholder="Pick a day"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="会员头像" class="Timg" prop="hyimg">
        <el-upload
          list-type="picture-card"
          action="http://demonuxtapi.dishait.cn/admin/s/upload"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <el-icon v-if="form.hyimg === ''"><Plus /></el-icon>

          <el-image v-if="form.hyimg !== ''" :src="form.hyimg" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <!-- <img class="el-upload-list__item-thumbnail" :src="form.hyimg" /> -->
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="delshow" title="会员删除" width="500" align-center>
    <span>此操作将永久删除该数据，删除后不可恢复，确定要继续吗？</span>
    <template #footer>
      <el-button @click="delshow = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep() {
  .el-pagination {
    justify-content: flex-end;
  }
  .Timg {
    width: 300px;
    height: 148px;
    overflow: hidden;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
.hygl {
  height: 100%;
  background-color: #fff;
  .hygl-top {
    text-align: center;
    padding: 8px;
  }
  .hygl-button {
    padding-top: 8px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
